import 'package:flutter/material.dart';
import 'package:word_range_client/pages/general/LoginView.dart';
import 'package:word_range_client/pages/general/UserAgreement.dart';
import 'package:word_range_client/pojo/Result.dart';
import 'package:word_range_client/widgets/general/Toastification.dart';

import '../../viewModels/UserViewModel.dart';


class RegisterView extends StatelessWidget {
  const RegisterView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("注册"),
      ),
      body: const _RegisterViewBody(),
    );
  }
}

class _RegisterViewBody extends StatefulWidget {
  const _RegisterViewBody({super.key});

  @override
  State<_RegisterViewBody> createState() => _RegisterViewBodyState();
}

class _RegisterViewBodyState extends State<_RegisterViewBody> {

  bool consentAgreement = false;

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _rePasswordController = TextEditingController();

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _passwordController.dispose();
    _rePasswordController.dispose();
    super.dispose();
  }

  Future<void> register() async {
    UserViewModel userViewModel = UserViewModel();
    Toastification toastification = Toastification(context: context);
    String name = _nameController.text;
    String phone = _phoneController.text;
    String password = _passwordController.text;
    String rePassword = _rePasswordController.text;


    if(password != rePassword){
      toastification.showError("两次密码输入的不一致");
      return;
    }

    try{
      Result result = await userViewModel.register(name, phone, password);
      if(result.code != 1){
        String msg = result.msg!;
        toastification.showError(msg);
        return;
      }
      toastification.showSuccess("注册成功，请登录");
      toLoginPage(phone,password);
    }catch(e){
      print(e);
      toastification.showError("网络错误");
    }

  }

  void toLoginPage(String phone,String password){
    Navigator.of(context).pushReplacement(MaterialPageRoute(
        builder: (context) => LoginView(phone: phone,password: password,))
    );
  }

  void toUserAgreementPage(){
    Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => const UserAgreement())
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 900),
          child: ListView(
            children: [
              const SizedBox(height: 20,),
              const Text("注册新账号",style: TextStyle(fontSize: 35,fontWeight: FontWeight.w600),),
              const SizedBox(height: 40,),
              TextField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: "用户名",
                  hintText: "这将作为您的昵称",
                  hintStyle: TextStyle(color: Colors.grey),
                  prefixIcon: Icon(Icons.people),
                  enabledBorder: UnderlineInputBorder(),
                ),
              ),
              TextField(
                controller: _phoneController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: "手机号",
                  hintText: "请输入您的手机号",
                  hintStyle: TextStyle(color: Colors.grey),
                  prefixIcon: Icon(Icons.phone),
                  enabledBorder: UnderlineInputBorder(),
                ),
              ),
              TextField(
                controller: _passwordController,
                keyboardType: TextInputType.visiblePassword,
                obscureText: true,
                decoration: const InputDecoration(
                  labelText: "密码",
                  hintText: "请输入密码",
                  hintStyle: TextStyle(color: Colors.grey),
                  prefixIcon: Icon(Icons.key),
                  enabledBorder: UnderlineInputBorder(),
                ),
              ),
              TextField(
                controller: _rePasswordController,
                keyboardType: TextInputType.visiblePassword,
                obscureText: true,
                decoration: const InputDecoration(
                  labelText: "确认密码",
                  hintText: "再次输入你的密码",
                  hintStyle: TextStyle(color: Colors.grey),
                  prefixIcon: Icon(Icons.password),
                  enabledBorder: UnderlineInputBorder(),
                ),
              ),
              SizedBox(
                height: 60,
                child: Row(
                  children: [
                    Checkbox(
                        value: consentAgreement,
                        checkColor: Theme.of(context).colorScheme.background,
                        onChanged: (value){
                          setState(() {
                            consentAgreement = ! consentAgreement;
                          });
                        }
                    ),
                    const Text("我已阅读并同意"),
                    TextButton(
                        onPressed: toUserAgreementPage,
                        child: const Text("《用户协议》")
                    )
                  ],
                ),
              ),
              Hero(
                  tag: "ApplyButton",
                  child: _RegisterButton(enable: consentAgreement,register: register,)
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _RegisterButton extends StatefulWidget {
  const _RegisterButton({super.key, this.enable = true, required this.register});
  final bool enable;
  final Function register;

  void _register(){
    register();
  }

  @override
  State<_RegisterButton> createState() => _RegisterButtonState();
}

class _RegisterButtonState extends State<_RegisterButton> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 55,
      width: MediaQuery.of(context).size.width,
      child: IgnorePointer(
        ignoring: ! widget.enable,
        child: ElevatedButton(
          onPressed: widget._register,
          style: ButtonStyle(
            shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15)
                )
            ),
            backgroundColor: MaterialStateProperty.all(
                widget.enable ? Theme.of(context).colorScheme.primary : Colors.grey
            ),
            foregroundColor: MaterialStateProperty.all(Theme.of(context).colorScheme.background),
            overlayColor: MaterialStateProperty.all(Theme.of(context).colorScheme.onPrimary),
          ),
          child: const Text("提交",style: TextStyle(fontSize: 20),),
        ),
      )
    );
  }
}



